﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections;
using System.Collections.Specialized;
using System.Web.Caching;
using System.IO;
using System.Security.Cryptography;

namespace Common
{
    public class Utility
    {
        /// <summary>
        /// 判断是否是数字
        /// </summary>
        /// <param name="Seat"></param>
        /// <returns>true是数字，false不是数字</returns>
        public static Boolean CheckNum(string Num)
        {
            int n;
            if (!int.TryParse(Num, out n))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// Base64编码类。
        /// 将byte[]类型转换成Base64编码的string类型。
        /// </summary>
        public class Base64Encoder
        {
            byte[] source;
            int length, length2;
            int blockCount;
            int paddingCount;
            public static Base64Encoder Encoder = new Base64Encoder();

            public Base64Encoder()
            {
            }

            private void init(byte[] input)
            {
                source = input;
                length = input.Length;
                if ((length % 3) == 0)
                {
                    paddingCount = 0;
                    blockCount = length / 3;
                }
                else
                {
                    paddingCount = 3 - (length % 3);
                    blockCount = (length + paddingCount) / 3;
                }
                length2 = length + paddingCount;
            }

            public string GetEncoded(byte[] input)
            {
                //初始化
                init(input);

                byte[] source2;
                source2 = new byte[length2];

                for (int x = 0; x < length2; x++)
                {
                    if (x < length)
                    {
                        source2[x] = source[x];
                    }
                    else
                    {
                        source2[x] = 0;
                    }
                }

                byte b1, b2, b3;
                byte temp, temp1, temp2, temp3, temp4;
                byte[] buffer = new byte[blockCount * 4];
                char[] result = new char[blockCount * 4];
                for (int x = 0; x < blockCount; x++)
                {
                    b1 = source2[x * 3];
                    b2 = source2[x * 3 + 1];
                    b3 = source2[x * 3 + 2];

                    temp1 = (byte)((b1 & 252) >> 2);

                    temp = (byte)((b1 & 3) << 4);
                    temp2 = (byte)((b2 & 240) >> 4);
                    temp2 += temp;

                    temp = (byte)((b2 & 15) << 2);
                    temp3 = (byte)((b3 & 192) >> 6);
                    temp3 += temp;

                    temp4 = (byte)(b3 & 63);

                    buffer[x * 4] = temp1;
                    buffer[x * 4 + 1] = temp2;
                    buffer[x * 4 + 2] = temp3;
                    buffer[x * 4 + 3] = temp4;

                }

                for (int x = 0; x < blockCount * 4; x++)
                {
                    result[x] = sixbit2char(buffer[x]);
                }


                switch (paddingCount)
                {
                    case 0: break;
                    case 1: result[blockCount * 4 - 1] = '='; break;
                    case 2: result[blockCount * 4 - 1] = '=';
                        result[blockCount * 4 - 2] = '=';
                        break;
                    default: break;
                }
                return new string(result);
            }
            private char sixbit2char(byte b)
            {
                char[] lookupTable = new char[64]{
                  'A','B','C','D','E','F','G','H','I','J','K','L','M',
                 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                 'a','b','c','d','e','f','g','h','i','j','k','l','m',
                 'n','o','p','q','r','s','t','u','v','w','x','y','z',
                 '0','1','2','3','4','5','6','7','8','9','+','/'};

                if ((b >= 0) && (b <= 63))
                {
                    return lookupTable[(int)b];
                }
                else
                {

                    return ' ';
                }
            }

        }

        /// <summary>
        /// Base64解码类
        /// 将Base64编码的string类型转换成byte[]类型
        /// </summary>
        public class Base64Decoder
        {
            char[] source;
            int length, length2, length3;
            int blockCount;
            int paddingCount;
            public static Base64Decoder Decoder = new Base64Decoder();

            public Base64Decoder()
            {
            }

            private void init(char[] input)
            {
                int temp = 0;
                source = input;
                length = input.Length;

                for (int x = 0; x < 2; x++)
                {
                    if (input[length - x - 1] == '=')
                        temp++;
                }
                paddingCount = temp;

                blockCount = length / 4;
                length2 = blockCount * 3;
            }

            public byte[] GetDecoded(string strInput)
            {
                //初始化
                init(strInput.ToCharArray());

                byte[] buffer = new byte[length];
                byte[] buffer2 = new byte[length2];

                for (int x = 0; x < length; x++)
                {
                    buffer[x] = char2sixbit(source[x]);
                }

                byte b, b1, b2, b3;
                byte temp1, temp2, temp3, temp4;

                for (int x = 0; x < blockCount; x++)
                {
                    temp1 = buffer[x * 4];
                    temp2 = buffer[x * 4 + 1];
                    temp3 = buffer[x * 4 + 2];
                    temp4 = buffer[x * 4 + 3];

                    b = (byte)(temp1 << 2);
                    b1 = (byte)((temp2 & 48) >> 4);
                    b1 += b;

                    b = (byte)((temp2 & 15) << 4);
                    b2 = (byte)((temp3 & 60) >> 2);
                    b2 += b;

                    b = (byte)((temp3 & 3) << 6);
                    b3 = temp4;
                    b3 += b;

                    buffer2[x * 3] = b1;
                    buffer2[x * 3 + 1] = b2;
                    buffer2[x * 3 + 2] = b3;
                }

                length3 = length2 - paddingCount;
                byte[] result = new byte[length3];

                for (int x = 0; x < length3; x++)
                {
                    result[x] = buffer2[x];
                }

                return result;
            }

            private byte char2sixbit(char c)
            {
                char[] lookupTable = new char[64]{  
                 'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
                 'O','P','Q','R','S','T','U','V','W','X','Y', 'Z',
                 'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
                 'o','p','q','r','s','t','u','v','w','x','y','z',
                 '0','1','2','3','4','5','6','7','8','9','+','/'};
                if (c == '=')
                    return 0;
                else
                {
                    for (int x = 0; x < 64; x++)
                    {
                        if (lookupTable[x] == c)
                            return (byte)x;
                    }

                    return 0;
                }

            }
        }
        //解码类结束
    }

    public class Utils
    {
        #region Request.Form获取值
        public static string Rf(string obj)
        {
            string Value = "";
            if (HttpContext.Current.Request.Form[obj] != null)
            {
                if (HttpContext.Current.Request.Form[obj] != "")
                {
                    Value = HttpContext.Current.Request.Form[obj].ToString().Trim();
                }
            }
            return Value;
        }

        public static string Rf(string obj, string tostring)
        {
            string Value = tostring;
            if (HttpContext.Current.Request.Form[obj] != null)
            {
                if (HttpContext.Current.Request.Form[obj] != "")
                {
                    Value = HttpContext.Current.Request.Form[obj].ToString().Trim();
                }
            }
            return Value;
        }
        #endregion

        #region Request.QueryString获取值
        public static string Rq(string obj)
        {
            string Value = "";
            if (HttpContext.Current.Request.QueryString[obj] != null)
            {
                if (HttpContext.Current.Request.QueryString[obj] != "")
                {
                    Value = HttpContext.Current.Request.QueryString[obj].ToString().Trim();
                }
            }
            return Value;
        }


        public static string Rq(string obj, string tostring)
        {
            string Value = tostring;
            if (HttpContext.Current.Request.QueryString[obj] != null)
            {
                if (HttpContext.Current.Request.QueryString[obj] != "")
                {
                    Value = HttpContext.Current.Request.QueryString[obj].ToString().Trim();
                }
            }
            return Value;
        }
        #endregion

        #region 加密
        public static string EncodeURIComponent(string key)
        {
            return DESEncrypt.Encrypt(key);
        }
        #endregion

        #region 解密
        public static string DecodeURIComponent(string key)
        {
            return DESEncrypt.Decrypt(key);
        }
        #endregion

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIPAddress()
        {
            string userIP = "";
            try
            {
                HttpRequest Request = HttpContext.Current.Request;
                // 如果使用代理，获取真实IP
                if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                    userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                else
                    userIP = Request.ServerVariables["REMOTE_ADDR"];
                if (userIP == null || userIP == "")
                    userIP = Request.UserHostAddress;
            }
            catch { }
            return userIP;
        }

        /// <summary>
        /// 获取UserAgent
        /// </summary>
        /// <returns></returns>
        public static string GetUserAgent()
        {
            string strUserAgent = "";
            try
            {
                strUserAgent = HttpContext.Current.Request.UserAgent.ToString();
            }
            catch { }
            return strUserAgent;
        }


        /// <summary>
        /// 本地时间转为UTC
        /// </summary>
        /// <param name="lacalTime"></param>
        /// <returns></returns>
        public static string LocalTime2GreenwishTime(DateTime lacalTime)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = lacalTime;
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return timeStamp;
        }
        /// <summary>
        /// UTC转为本地时间
        /// </summary>
        /// <param name="greenwishTime"></param>
        /// <returns></returns>
        public static DateTime GreenwishTime2LocalTime(string greenwishTime)
        {
            string timeStamp = greenwishTime;
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

        /// <summary>
        /// 生成随机字母与数字
        /// </summary>
        /// <param name="Length">生成长度</param>
        /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
        /// <returns></returns>
        public string GenerateCheckCode(int Length, bool Sleep)
        {
            if (Sleep)
                System.Threading.Thread.Sleep(3);
            char[] Pattern = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
            string result = "";
            int n = Pattern.Length;
            System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
            for (int i = 0; i < Length; i++)
            {
                int rnd = random.Next(0, n);
                result += Pattern[rnd];
            }
            return result;
        }


        /// <summary>
        /// 生成缩缩略图
        /// </summary>
        /// <param name="imagePath">原图路径</param>
        /// <param name="savePath">缩略图存储路径</param>
        /// <param name="wid">缩略图宽</param>
        /// <param name="hid">缩略图高</param>
        public static void BreviaryImg(string imagePath, string savePath, int wid, int hid)
        {
            string originalImagePath = imagePath;
            string thumbnailPath = savePath;
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            //int towidth = wid;
            //int toheight = hid;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(wid, hid);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, wid, hid), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

            try
            {

                //以原格式保存缩略图
                bitmap.Save(thumbnailPath, originalImage.RawFormat);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 服务替换时间规则
        /// </summary>
        /// <param name="AddTime"></param>
        /// <returns></returns>
        public static string GetReplaceDate(string AddTime)
        {
            string value = "";
            try
            {
                if (string.IsNullOrWhiteSpace(AddTime))
                    return "";
                DateTime dtToday = Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd"));

                DateTime dtDate = Convert.ToDateTime(AddTime);

                DateTime dtAddDate = Convert.ToDateTime(dtDate.ToString("yyyy-MM-dd"));
                TimeSpan t = dtToday - dtAddDate;

                int iday = t.Days;
                if (iday <= 1)
                {
                    int itoday_day = dtToday.Day;
                    int idate_day = dtDate.Day;
                    if (itoday_day != idate_day)
                        iday = 2;
                }

                int ihour = dtDate.Hour;
                int iminute = dtDate.Minute;
                if (iday > 30)
                {
                    value = dtDate.Year.ToString() + "年" + dtDate.Month.ToString() + "月" + dtDate.Day.ToString() + "日";
                }
                else if (iday > 1)
                {
                    value = dtDate.Month.ToString() + "月" + dtDate.Day.ToString() + "日";
                    if (ihour < 8)
                        value += "早上";
                    else if (ihour < 12)
                        value += "上午";
                    else if (ihour >= 18)
                        value += "晚上";
                    else
                        value += "下午";

                    value += dtDate.ToString("h:mm");
                }
                else
                {
                    if (ihour < 8)
                        value += "早上";
                    else if (ihour < 12)
                        value = "上午";
                    else if (ihour >= 18)
                        value = "晚上";
                    else
                        value = "下午";
                    value += dtDate.ToString("h:mm");
                }

            }
            catch { }
            return value;
        }
    }

    #region Cookie操作类
    /// <summary>
    /// Cookie操作类
    /// </summary>
    public static class Cookie
    {
        public static string TimeString = "";
        /// 创建COOKIE对象并赋Value值
        /// <summary>
        /// 创建COOKIE对象并赋Value值，修改COOKIE的Value值也用此方法，因为对COOKIE修改必须重新设Expires
        /// </summary>
        /// <param name="strCookieName">COOKIE对象名</param>
        /// <param name="iExpires">COOKIE对象有效时间（秒数），1表示永久有效，0和负数都表示不设有效时间，大于等于2表示具体有效秒数，31536000秒=1年=(60*60*24*365)，</param>
        /// <param name="strValue">COOKIE对象Value值</param>
        public static void SetObj(string strCookieName, int iExpires, string strValue)
        {
            // HttpContext.Current.Response.AddHeader("P3P", "CP=NON DSP COR CURa ADMa DEVa TAIa PSAa PSDa IVAa IVDa CONa HISa TELa OTPa OUR UNRa IND UNI COM NAV INT DEM CNT PRE LOC");
            HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
            // objCookie.Value = Utils.Common.EncodeURIComponent(strValue.Trim());
            objCookie.Value = HttpContext.Current.Server.UrlDecode(strValue.Trim());
            objCookie.Domain = TimeString;
            if (iExpires > 0)
            {
                if (iExpires == 1)
                {
                    objCookie.Expires = DateTime.MaxValue;
                }
                else
                {
                    objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                }
            }
            HttpContext.Current.Response.Cookies.Add(objCookie);
        }

        public static void SetCookie(string strCookieName, double iExpires, string strValue)
        {
            if (HttpContext.Current.Request.Cookies[strCookieName] != null)
            {
                Cookie.Del(strCookieName);
            }
            HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
            objCookie.Value = HttpContext.Current.Server.UrlDecode(strValue.Trim());
            objCookie.Domain = TimeString;
            if (iExpires > 0)
            {
                objCookie.Expires = DateTime.Now.AddDays(iExpires);

            }
            HttpContext.Current.Response.Cookies.Add(objCookie);
        }

        /// 创建COOKIE对象并赋多个KEY键值
        /// <summary>
        /// 创建COOKIE对象并赋多个KEY键值
        /// 设键/值如下：
        /// NameValueCollection myCol = new NameValueCollection();
        /// myCol.Add("red", "rojo");
        /// myCol.Add("green", "verde");
        /// myCol.Add("blue", "azul");
        /// myCol.Add("red", "rouge");   结果“red:rojo,rouge；green:verde；blue:azul”
        /// </summary>
        /// <param name="strCookieName">COOKIE对象名</param>
        /// <param name="iExpires">COOKIE对象有效时间（秒数），1表示永久有效，0和负数都表示不设有效时间，大于等于2表示具体有效秒数，31536000秒=1年=(60*60*24*365)，</param>
        /// <param name="KeyValue">键/值对集合</param>
        public static void SetObj(string strCookieName, int iExpires, NameValueCollection KeyValue)
        {
            if (HttpContext.Current.Request.Cookies[strCookieName] != null)
            {
                Cookie.Del(strCookieName);
            }
            HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
            foreach (String key in KeyValue.AllKeys)
            {
                objCookie[key] = Utils.EncodeURIComponent(KeyValue[key].Trim());
            }
            objCookie.Domain = TimeString;
            if (iExpires > 0)
            {
                if (iExpires == 1)
                {
                    objCookie.Expires = DateTime.MaxValue;
                }
                else
                {
                    objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                }
            }
            HttpContext.Current.Response.Cookies.Add(objCookie);
        }
        /// 创建COOKIE对象并赋Value值
        /// <summary>
        /// 创建COOKIE对象并赋Value值，修改COOKIE的Value值也用此方法，因为对COOKIE修改必须重新设Expires
        /// </summary>
        /// <param name="strCookieName">COOKIE对象名</param>
        /// <param name="iExpires">COOKIE对象有效时间（秒数），1表示永久有效，0和负数都表示不设有效时间，大于等于2表示具体有效秒数，31536000秒=1年=(60*60*24*365)，</param>
        /// <param name="strDomain">作用域</param>
        /// <param name="strValue">COOKIE对象Value值</param>
        public static void SetObj(string strCookieName, int iExpires, string strValue, string strDomain)
        {
            if (HttpContext.Current.Request.Cookies[strCookieName] != null)
            {
                Cookie.Del(strCookieName);
            }
            HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
            objCookie.Value = Utils.EncodeURIComponent(strValue.Trim());
            objCookie.Domain = strDomain.Trim();
            if (iExpires > 0)
            {
                if (iExpires == 1)
                {
                    objCookie.Expires = DateTime.MaxValue;
                }
                else
                {
                    objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                }
            }
            HttpContext.Current.Response.Cookies.Add(objCookie);
        }

        public static void SetObjNull(string strCookieName)
        {
            HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
            objCookie.Value = null;

            HttpContext.Current.Response.Cookies.Add(objCookie);
        }
        /// 创建COOKIE对象并赋多个KEY键值
        /// <summary>
        /// 创建COOKIE对象并赋多个KEY键值
        /// 设键/值如下：
        /// NameValueCollection myCol = new NameValueCollection();
        /// myCol.Add("red", "rojo");
        /// myCol.Add("green", "verde");
        /// myCol.Add("blue", "azul");
        /// myCol.Add("red", "rouge");   结果“red:rojo,rouge；green:verde；blue:azul”
        /// </summary>
        /// <param name="strCookieName">COOKIE对象名</param>
        /// <param name="iExpires">COOKIE对象有效时间（秒数），1表示永久有效，0和负数都表示不设有效时间，大于等于2表示具体有效秒数，31536000秒=1年=(60*60*24*365)，</param>
        /// <param name="strDomain">作用域</param>
        /// <param name="KeyValue">键/值对集合</param>
        public static void SetObj(string strCookieName, int iExpires, NameValueCollection KeyValue, string strDomain)
        {
            HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
            foreach (String key in KeyValue.AllKeys)
            {
                objCookie[key] = Utils.EncodeURIComponent(KeyValue[key].Trim());
            }
            objCookie.Domain = strDomain.Trim();
            if (iExpires > 0)
            {
                if (iExpires == 1)
                {
                    objCookie.Expires = DateTime.MaxValue;
                }
                else
                {
                    objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                }
            }
            HttpContext.Current.Response.Cookies.Add(objCookie);
        }

        /// 读取Cookie某个对象的Value值
        /// <summary>
        /// 读取Cookie某个对象的Value值，返回Value值，如果对象本就不存在，则返回字符串"CookieNonexistence"
        /// </summary>
        /// <param name="strCookieName">Cookie对象名称</param>
        /// <returns>Value值，如果对象本就不存在，则返回字符串"CookieNonexistence"</returns>
        public static string GetValue(string strCookieName)
        {
            if (HttpContext.Current.Request.Cookies[strCookieName] == null)
            {
                return "";
            }
            else
            {
                return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[strCookieName].Value);
            }
        }
        /// 读取Cookie某个对象的某个Key键的键值
        /// <summary>
        /// 读取Cookie某个对象的某个Key键的键值，返回Key键值，如果对象本就不存在，则返回字符串"CookieNonexistence"，如果Key键不存在，则返回字符串"KeyNonexistence"
        /// </summary>
        /// <param name="strCookieName">Cookie对象名称</param>
        /// <param name="strKeyName">Key键名</param>
        /// <returns>Key键值，如果对象本就不存在，则返回字符串"CookieNonexistence"，如果Key键不存在，则返回字符串"KeyNonexistence"</returns>
        public static string GetValue(string strCookieName, string strKeyName)
        {
            if (HttpContext.Current.Request.Cookies[strCookieName] == null)
            {
                return "";
            }
            else
            {
                string strObjValue = Utils.DecodeURIComponent(HttpContext.Current.Request.Cookies[strCookieName].Value);
                string strKeyName2 = strKeyName + "=";
                if (strObjValue.IndexOf(strKeyName2) == -1)
                {
                    return "";
                }
                else
                {
                    return Utils.DecodeURIComponent(HttpContext.Current.Request.Cookies[strCookieName][strKeyName]);
                }
            }
        }

        /// 修改某个COOKIE对象某个Key键的键值 或 给某个COOKIE对象添加Key键 都调用本方法
        /// <summary>
        /// 修改某个COOKIE对象某个Key键的键值 或 给某个COOKIE对象添加Key键 都调用本方法，操作成功返回字符串"success"，如果对象本就不存在，则返回字符串"CookieNonexistence"。
        /// </summary>
        /// <param name="strCookieName">Cookie对象名称</param>
        /// <param name="strKeyName">Key键名</param>
        /// <param name="KeyValue">Key键值</param>
        /// <param name="iExpires">COOKIE对象有效时间（秒数），1表示永久有效，0和负数都表示不设有效时间，大于等于2表示具体有效秒数，31536000秒=1年=(60*60*24*365)。注意：虽是修改功能，实则重建覆盖，所以时间也要重设，因为没办法获得旧的有效期</param>
        /// <returns>如果对象本就不存在，则返回字符串"CookieNonexistence"，如果操作成功返回字符串"success"。</returns>
        public static string Edit(string strCookieName, string strKeyName, string KeyValue, int iExpires)
        {
            if (HttpContext.Current.Request.Cookies[strCookieName] == null)
            {
                return "CookieNonexistence";
            }
            else
            {
                HttpCookie objCookie = HttpContext.Current.Request.Cookies[strCookieName];
                objCookie[strKeyName] = Utils.EncodeURIComponent(KeyValue.Trim());
                objCookie.Domain = TimeString;
                if (iExpires > 0)
                {
                    if (iExpires == 1)
                    {
                        objCookie.Expires = DateTime.MaxValue;
                    }
                    else
                    {
                        objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                    }
                }
                HttpContext.Current.Response.Cookies.Add(objCookie);
                return "success";
            }
        }

        /// 删除COOKIE对象
        /// <summary>
        /// 删除COOKIE对象
        /// </summary>
        /// <param name="strCookieName">Cookie对象名称</param>
        public static void Del(string strCookieName)
        {
            if (HttpContext.Current.Request.Cookies[strCookieName] != null)
            {
                HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
                objCookie.Domain = TimeString;
                TimeSpan ts = new TimeSpan(-5, 0, 0, 0);
                objCookie.Expires = DateTime.Now.Add(ts);//删除整个Cookie，只要把过期时间设置为现在
                //objCookie.Expires = DateTime.Now.AddYears(-5);
                HttpContext.Current.Response.Cookies.Add(objCookie);
            }
        }
        /// 删除某个COOKIE对象某个Key子键
        /// <summary>
        /// 删除某个COOKIE对象某个Key子键，操作成功返回字符串"success"，如果对象本就不存在，则返回字符串"CookieNonexistence"
        /// </summary>
        /// <param name="strCookieName">Cookie对象名称</param>
        /// <param name="strKeyName">Key键名</param>
        /// <param name="iExpires">COOKIE对象有效时间（秒数），1表示永久有效，0和负数都表示不设有效时间，大于等于2表示具体有效秒数，31536000秒=1年=(60*60*24*365)。注意：虽是修改功能，实则重建覆盖，所以时间也要重设，因为没办法获得旧的有效期</param>
        /// <returns>如果对象本就不存在，则返回字符串"CookieNonexistence"，如果操作成功返回字符串"success"。</returns>
        public static string Del(string strCookieName, string strKeyName, int iExpires)
        {
            if (HttpContext.Current.Request.Cookies[strCookieName] == null)
            {
                return "CookieNonexistence";
            }
            else
            {
                HttpCookie objCookie = HttpContext.Current.Request.Cookies[strCookieName];
                objCookie.Values.Remove(strKeyName);
                objCookie.Domain = TimeString;
                if (iExpires > 0)
                {
                    if (iExpires == 1)
                    {
                        objCookie.Expires = DateTime.MaxValue;
                    }
                    else
                    {
                        objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                    }
                }
                HttpContext.Current.Response.Cookies.Add(objCookie);
                return "success";
            }
        }
    }
    #endregion

    #region Session操作类
    /// Session操作类
    /// <summary>
    /// Session操作类
    /// </summary>
    public static class SessionCustom
    {
        /// 添加Session，调动有效期默认为23分钟
        /// <summary>
        /// 添加Session，调动有效期默认为23分钟
        /// </summary>
        /// <param name="strSessionName">Session对象名称</param>
        /// <param name="strValue">Session值</param>
        public static void Add(string strSessionName, string strValue)
        {
            HttpContext.Current.Session[strSessionName] = strValue;
            HttpContext.Current.Session.Timeout = 60;
        }
        /// 添加Session
        /// <summary>
        /// 添加Session
        /// </summary>
        /// <param name="strSessionName">Session对象名称</param>
        /// <param name="strValue">Session值</param>
        /// <param name="iExpires">调动有效期（分钟）</param>
        public static void Add(string strSessionName, string strValue, int iExpires)
        {
            HttpContext.Current.Session[strSessionName] = strValue;
            HttpContext.Current.Session.Timeout = iExpires;
        }

        /// 读取某个Session对象值
        /// <summary>
        /// 读取某个Session对象值
        /// </summary>
        /// <param name="strSessionName">Session对象名称</param>
        /// <returns>Session对象值</returns>
        public static string Get(string strSessionName)
        {
            if (HttpContext.Current.Session[strSessionName] == null)
            {
                return null;
            }
            else
            {
                return HttpContext.Current.Session[strSessionName].ToString();
            }
        }

        /// 删除某个Session对象
        /// <summary>
        /// 删除某个Session对象
        /// </summary>
        /// <param name="strSessionName">Session对象名称</param>
        public static void Del(string strSessionName)
        {
            HttpContext.Current.Session[strSessionName] = null;
        }
    }
    #endregion

    #region Cache操作类
    /// Cache操作类
    /// <summary>
    /// Cache操作类
    /// </summary>
    public static class CacheCustom
    {
        /// 简单创建/修改Cache，前提是这个值是字符串形式的
        /// <summary>
        /// 简单创建/修改Cache，前提是这个值是字符串形式的
        /// </summary>
        /// <param name="strCacheName">Cache名称</param>
        /// <param name="strValue">Cache值</param>
        /// <param name="iExpires">有效期，秒数（使用的是当前时间+秒数得到一个绝对到期值）</param>
        /// <param name="priority">保留优先级，1最不会被清除，6最容易被内存管理清除（1:NotRemovable；2:High；3:AboveNormal；4:Normal；5:BelowNormal；6:Low）</param>
        public static void Insert(string strCacheName, string strValue, int iExpires, int priority)
        {
            TimeSpan ts = new TimeSpan(0, 0, iExpires);
            CacheItemPriority cachePriority;
            switch (priority)
            {
                case 6:
                    cachePriority = CacheItemPriority.Low;
                    break;
                case 5:
                    cachePriority = CacheItemPriority.BelowNormal;
                    break;
                case 4:
                    cachePriority = CacheItemPriority.Normal;
                    break;
                case 3:
                    cachePriority = CacheItemPriority.AboveNormal;
                    break;
                case 2:
                    cachePriority = CacheItemPriority.High;
                    break;
                case 1:
                    cachePriority = CacheItemPriority.NotRemovable;
                    break;
                default:
                    cachePriority = CacheItemPriority.Default;
                    break;
            }
            HttpContext.Current.Cache.Insert(strCacheName, strValue, null, DateTime.Now.Add(ts), System.Web.Caching.Cache.NoSlidingExpiration, cachePriority, null);
        }

        /// 简单读书Cache对象的值，前提是这个值是字符串形式的
        /// <summary>
        /// 简单读书Cache对象的值，前提是这个值是字符串形式的
        /// </summary>
        /// <param name="strCacheName">Cache名称</param>
        /// <returns>Cache字符串值</returns>
        public static string Get(string strCacheName)
        {
            return HttpContext.Current.Cache[strCacheName].ToString();
        }

        /// 删除Cache对象
        /// <summary>
        /// 删除Cache对象
        /// </summary>
        /// <param name="strCacheName">Cache名称</param>
        public static void Del(string strCacheName)
        {
            HttpContext.Current.Cache.Remove(strCacheName);
        }

    }
    #endregion

    #region 加密
    /// <summary>
    /// DES加密/解密类。
    /// </summary>
    public class DESEncrypt
    {
        public DESEncrypt()
        {
        }

        #region ========加密========

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, "litianping");
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion

        #region ========解密========


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, "litianping");
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

        #endregion


    }

    /// <summary>    
    /// 对称加密算法类    
    /// </summary>    
    public class SymmetricMethod
    {
        private SymmetricAlgorithm mobjCryptoService;
        private string Key;
        /// <summary>    
        /// 对称加密类的构造函数    
        /// </summary>    
        public SymmetricMethod()
        {
            mobjCryptoService = new RijndaelManaged();
            Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
        }
        /// <summary>    
        /// 获得密钥    
        /// </summary>    
        /// <returns>密钥</returns>    
        private byte[] GetLegalKey()
        {
            string sTemp = Key;
            mobjCryptoService.GenerateKey();
            byte[] bytTemp = mobjCryptoService.Key;
            int KeyLength = bytTemp.Length;
            if (sTemp.Length > KeyLength)
                sTemp = sTemp.Substring(0, KeyLength);
            else if (sTemp.Length < KeyLength)
                sTemp = sTemp.PadRight(KeyLength, ' ');
            return ASCIIEncoding.ASCII.GetBytes(sTemp);
        }
        /// <summary>    
        /// 获得初始向量IV    
        /// </summary>    
        /// <returns>初试向量IV</returns>    
        private byte[] GetLegalIV()
        {
            string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
            mobjCryptoService.GenerateIV();
            byte[] bytTemp = mobjCryptoService.IV;
            int IVLength = bytTemp.Length;
            if (sTemp.Length > IVLength)
                sTemp = sTemp.Substring(0, IVLength);
            else if (sTemp.Length < IVLength)
                sTemp = sTemp.PadRight(IVLength, ' ');
            return ASCIIEncoding.ASCII.GetBytes(sTemp);
        }
        /// <summary>    
        /// 加密方法    
        /// </summary>    
        /// <param name="Source">待加密的串</param>    
        /// <returns>经过加密的串</returns>    
        public string Encrypto(string Source)
        {
            byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
            MemoryStream ms = new MemoryStream();
            mobjCryptoService.Key = GetLegalKey();
            mobjCryptoService.IV = GetLegalIV();
            ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();
            ms.Close();
            byte[] bytOut = ms.ToArray();
            return Convert.ToBase64String(bytOut);
        }
        /// <summary>    
        /// 解密方法    
        /// </summary>    
        /// <param name="Source">待解密的串</param>    
        /// <returns>经过解密的串</returns>    
        public string Decrypto(string Source)
        {
            byte[] bytIn = Convert.FromBase64String(Source);
            MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
            mobjCryptoService.Key = GetLegalKey();
            mobjCryptoService.IV = GetLegalIV();
            ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            return sr.ReadToEnd();
        }
    }

    #endregion

    public class APIJsonData<T>
    {
        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static T DataDecode(string JsonData)
        {
            T requestModel = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(JsonData);
          
            if (requestModel != null)
            {
                foreach (System.Reflection.PropertyInfo p in requestModel.GetType().GetProperties())
                {
                    if (p.PropertyType == typeof(string))
                    {
                        if (p.GetValue(requestModel, null) != null&&p.CanWrite==true)
                        {
                            string s = p.GetValue(requestModel, null).ToString();
                            s = Common.StringHelper.UrlDecode(s);
                            p.SetValue(requestModel, s, null);
                        }
                    }
                }
            }
            return requestModel;

        }

        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static T DataDecode(T requestModel)
        {
            //T requestModel = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(JsonData);

            if (requestModel != null)
            {
                foreach (System.Reflection.PropertyInfo p in requestModel.GetType().GetProperties())
                {
                    if (p.PropertyType == typeof(string))
                    {
                        if (p.GetValue(requestModel, null) != null && p.CanWrite == true)
                        {
                            string s = p.GetValue(requestModel, null).ToString();
                            s = Common.StringHelper.UrlDecode(s);
                            p.SetValue(requestModel, s, null);
                        }
                    }
                }
            }
            return requestModel;
        }

        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="JsonData"></param>
        /// <returns></returns>
        public static IList<T> DataDecode(IList<T> list)
        {        
            if (list != null && list.Count > 0)
            {
                //int i=0;
                foreach (var t in list)
                {
                    //i = i + 1; 
                    foreach (System.Reflection.PropertyInfo p in t.GetType().GetProperties())
                    {
                        if (p.PropertyType == typeof(string))
                        {
                            //string s = p.GetValue(t, null) == null ? "" : p.GetValue(t, null).ToString();
                            //if (p.CanWrite == true)
                            //{
                            //    s = Common.StringHelper.UrlEncode(s);
                            //    p.SetValue(t, s, null);
                            //}

                            if (p.GetValue(t, null) != null && p.CanWrite == true)
                             {
                                 string s = p.GetValue(t, null).ToString();
                                 s = Common.StringHelper.UrlDecode(s);
                                 p.SetValue(t, s, null);
                             }
                        }
                    }
                }
            }
            return list;
        }
        /// <summary>
        /// 编码
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T DataEncode(T t)
        {
            if (t != null)
            {
                foreach (System.Reflection.PropertyInfo p in t.GetType().GetProperties())
                {
                    if (p.PropertyType == typeof(string))
                    {
                        if (p.GetValue(t, null) != null)
                        {
                            string s =p.GetValue(t, null)==null?"": p.GetValue(t, null).ToString();
                            if (p.CanWrite==true)
                            {
                                p.SetValue(t, Common.StringHelper.UrlEncode(s), null);
                            }
                        }
                    }
                }
            }
            return t;
        }
        /// <summary>
        /// 编码
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static IList<T> IListEncode(IList<T> list)
        {
            if (list != null && list.Count > 0)
            {
                //int i=0;
                foreach (var t in list)
                {
                    //i = i + 1; 
                    foreach (System.Reflection.PropertyInfo p in t.GetType().GetProperties())
                    {
                        if (p.PropertyType == typeof(string))
                        {
                            string s = p.GetValue(t, null)==null?"": p.GetValue(t, null).ToString();
                            if (p.CanWrite==true)
                            {
                                s=Common.StringHelper.UrlEncode(s);
                                p.SetValue(t,s, null);
                            }
                        }
                    }
                }
            }
            return list;
        }
    }
}
